<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" @ok="handleSubmit">
    <BasicForm @register="registerForm">
      <template #range="{ model, field }">
        <div v-for="(item, index) in model[field]" :key="index" class="range-list">
          <Space class="input-box">
            <Form.Item :name="['measureDataValueDTOList', index, 'dataTypeId']">
              <Select v-model:value="item.dataTypeId" placeholder="请选择" labelInValue
                @change="() => handleChangeDataType(index)" :options="dataTypeOptions">
              </Select>
            </Form.Item>
            <Form.Item :name="['measureDataValueDTOList', index, 'measureValue']">
              <Select v-if="item.dataTypeId?.option?.dictItemList && item.dataTypeId.option.dictItemList.length > 0"
                v-model:value="item.measureValue" placeholder="请选择" :options="item.dataTypeId.option.dictItemList"
                :fieldNames="valueFieldsName" @change="validList">
              </Select>
              <Input v-else v-model:value="item.measureValue" placeholder="请输入" @change="validList" />
            </Form.Item>
          </Space>
          <Form.Item>
            <Space>
              <Button :icon="h(PlusOutlined)" @click="handleAddLine(index)"></Button>
              <Button :icon="h(MinusOutlined)" danger :disabled="model[field].length === 1"
                @click="handleRemoveLine(index)"></Button>
            </Space>
          </Form.Item>
        </div>
      </template>
    </BasicForm>
  </BasicModal>
</template>
<script lang="ts" setup>
import { ref, computed, unref, h } from 'vue';
import { BasicModal, useModalInner } from '@/components/Modal';
import { BasicForm, FormSchema, useForm } from '@/components/Form';
import { addMeasureData } from '@/api/collection/data';
import { Form, Space, Select, Input, Button, message } from 'ant-design-vue';
import { PlusOutlined, MinusOutlined } from '@ant-design/icons-vue';
import {
  getDeviceList,
  getDevicePropertyDataTypeList,
  getDeviceTypeList,
} from '@/api/collection/device'

import { cloneDeep } from 'lodash-es'

defineOptions({ name: 'DataTyeModal' });

const emit = defineEmits(['success', 'register']);

const isUpdate = ref(true);
const rowId = ref('');
const dataTypeOptions = ref([])
const valueFieldsName = { label: 'itemName', value: 'itemId' }

const dataFormSchema: FormSchema[] = [
  {
    label: '设备类型',
    field: 'dataTypeId',
    component: 'ApiSelect',
    componentProps: ({ formModel, formActionType }) => {
      return {
        api: getDeviceTypeList,
        labelField: 'name',
        valueField: 'id',
        onChange: async (e, v) => {
          const ret = await getDeviceList({
            type: v.code,
          })
          const floorOptions = ret.map((item) => ({
            value: item.id,
            label: item.name,
            key: item.id,
          }))
          formModel.deviceId = undefined //  reset deviceId value
          formModel.measureDataValueDTOList = [{
            dataTypeId: undefined,
            measureValue: undefined
          }]
          clearValidate('measureDataValueDTOList')
          const { updateSchema } = formActionType
          updateSchema({
            field: 'deviceId',
            componentProps: {
              options: floorOptions,
              onChange: async (e, v) => {
                const dtItem = await getDevicePropertyDataTypeList({ deviceId: e })
                const dataTypeItemOptions = dtItem.map((item) => ({
                  value: item.id,
                  label: item.name,
                  key: item.id,
                  dictItemList: item.dictItemList,
                }))
                dataTypeOptions.value = dataTypeItemOptions
                formModel.measureDataValueDTOList = [{
                  dataTypeId: undefined,
                  measureValue: undefined
                }]
                clearValidate('measureDataValueDTOList')
              },
            },
          })
        },
      }
    },
    required: true,
  },
  {
    field: 'deviceId',
    label: '设备名称',
    component: 'Select',
    componentProps: {
      options: [],
    },
    required: true,
  },
  {
    field: 'measureDataValueDTOList',
    label: '设备参数',
    slot: 'range',
    required: true,
    defaultValue: [
      {
        dataTypeId: undefined,
        measureValue: undefined,
      },
    ],
    rules: [
      {
        required: true,
        message: '请配置适用范围',
      },
      {
        validator(_, value) {
          console.log('%c [ value ]-151', 'font-size:13px; background:pink; color:#bf2c9f;', value)
          return new Promise((resolve, reject) => {
            const reg = /^[\u4E00-\u9FA5A-Za-z0-9_]+$/
            let hasEmpty = false
            let hasError = false
            for (let item of value) {
              if (!item.dataTypeId || !item.measureValue) {
                hasEmpty = true
                break
              }
              if (!reg.test(item.measureValue)) {
                hasError = true
              }
            }
            if (!value.length) {
              reject('请配置设备参数')
            } else if (hasEmpty) {
              reject('请完善设备参数')
            } else if (hasError) {
              reject('参数值为数字、字母、汉字')
            } else {
              return resolve()
            }
          })
        },
      },
    ],
  },
]

const [registerForm, { setFieldsValue, resetFields, validate, validateFields, getFieldsValue, clearValidate }] = useForm({
  labelWidth: 100,
  baseColProps: { span: 24 },
  schemas: dataFormSchema,
  showActionButtonGroup: false,
  actionColOptions: {
    span: 23,
  },
});

const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
  resetFields();
  setModalProps({ confirmLoading: false });
  isUpdate.value = !!data?.isUpdate;

  if (unref(isUpdate)) {
    rowId.value = data.record.id;
    setFieldsValue({
      ...data.record,
    });
  }
});

const getTitle = computed(() => (!unref(isUpdate) ? '录入采集数据' : '修改采集数据'));

const handleChangeDataType = (index) => {
  const { measureDataValueDTOList } = getFieldsValue()
  const newData = cloneDeep(measureDataValueDTOList)
  newData[index].measureValue = undefined
  setFieldsValue({
    measureDataValueDTOList: newData
  })
};

function validList() {
  validateFields(['measureDataValueDTOList'])
}

// 适用范围添加一行
function handleAddLine(index) {
  const { measureDataValueDTOList } = getFieldsValue()
  const newData = cloneDeep(measureDataValueDTOList)
  newData.splice(
    index + 1,
    0,
    {
      dataTypeId: undefined,
      measureValue: undefined,
    }
  )
  setFieldsValue({
    measureDataValueDTOList: newData
  })
}
// 移除一行
function handleRemoveLine(index) {
  const { measureDataValueDTOList } = getFieldsValue()
  const newData = cloneDeep(measureDataValueDTOList)
  newData.splice(index, 1)
  setFieldsValue({
    measureDataValueDTOList: newData
  })
}

async function handleSubmit() {
  try {
    const values = await validate();
    const measureDataValueDTOList = values.measureDataValueDTOList.map(item => ({
      ...item,
      dataTypeId: item.dataTypeId.value
    }))
    setModalProps({ confirmLoading: true });
    // TODO custom api
    addMeasureData({ ...values, measureDataValueDTOList }).then(res => {
      message.success('录入成功')
      closeModal();
      emit('success', { isUpdate: unref(isUpdate), values: { ...values, id: rowId.value } });

    })
    // console.log(values, ret);
  } finally {
    setModalProps({ confirmLoading: false });
  }
}
</script>

<style lang="scss">
.range-list {
  display: flex;
  justify-content: space-between;

  &:last-child {
    .ant-form-item {
      margin-bottom: 0;
    }
  }

  .input-box {
    flex: 1;
    margin-right: 8px;

    .ant-space-item {
      flex: 1;
    }
  }
}
</style>